//
//  WebAPI.m
//  WeChatHelper
//
//  Created by bang yi bang on 14-3-20.
//  Copyright (c) 2014年 bang yi bang. All rights reserved.

#import "WebAPI.h"
#import "EncoderMd5.h"
#import "JSONKit.h"
#import "DateCommand.h"
//#import "MKNetworkKit.h" //请求框架
#import "Commtools.h"

static AFHTTPRequestOperationManager *requestManager;
@interface WebAPI ()
{
    
}
@end

@implementation WebAPI
//@synthesize manager = requestManager;



+  (void) webAPISignAddMd5tWithNote:(NSString *)note parm:(NSDictionary *)parm completed:(WebAPIBlockRequest)complete
{
    WebAPI *webAPI = [WebAPI defaultManager];
    
    
    int time=[[NSDate date] timeIntervalSince1970];
    


    
//    NSString * s=@"time=1432794838&key=syinchung@20150330";
//    
//    NSString* d=[EncoderMd5 getMd5_32Bit_String:s];
//    
//    
//    NSLog(@"------------=============+++++%@",d);


    
    NSString *signString;
    
    
    signString=[NSString stringWithFormat:@"%@=%d&key=syinchung@20150330",@"time",time];
    
    
    signString=[EncoderMd5 getMd5_32Bit_String:signString];
    
    
    NSMutableDictionary *parms;
    
    parms=[parm mutableCopy];
    
    [parms setObject:signString forKey:@"sign"];
    [parms setObject:[NSString stringWithFormat:@"%d",time] forKey:@"time"];
    
    
   
  [webAPI postWebAPI:parms withPath:kUrl andMethodNode:note completed:complete];
}



+(NSString *)getSignString
{

    int time=[[NSDate date] timeIntervalSince1970];

    
    
    NSString *signString;
    
    
    signString=[NSString stringWithFormat:@"%@=%d&key=syinchung@20150330",@"time",time];
    
    
    signString=[EncoderMd5 getMd5_32Bit_String:signString];


    

    return signString;
}











+ (WebAPI *) defaultManager
{
    return [[self alloc] init];
}

- (id) init {
    self = [super init];
    if (self) {
        static dispatch_once_t onceToken ;
        dispatch_once (&onceToken,^{
            requestManager = [AFHTTPRequestOperationManager manager];
        });
    }
    return self;
}

- (void) setResponseSerializer:(AFHTTPResponseSerializer *)serializer
{
    requestManager.responseSerializer = serializer;
}

- (void) setHeader:(NSString *)value forKey:(NSString *)key
{
    [requestManager.requestSerializer setValue:value forHTTPHeaderField:key];
}

- (void) postWebAPI:(NSDictionary *)params withPath:(NSString *)path andMethodNode:(NSString *)node completed:(WebAPIBlockRequest)complete
{
    _complete = complete;
    
    NSString *url = [NSString stringWithFormat:@"%@/%@",path,node];
    
    
    requestManager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    
    
    requestManager.requestSerializer = [AFHTTPRequestSerializer serializer];
    
    requestManager.responseSerializer = [AFHTTPResponseSerializer serializer];

    
    
    NSLog(@"请求参数－－－－%@-----%@",url,params);
    
    


    
    
    [requestManager POST:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (_complete) {
            
            
            
            if ([responseObject isKindOfClass:[NSDictionary class]]) {
                
                
                
                
                 _complete(1,operation,responseObject);
                
                
                
                
            }
            
            if ([responseObject isKindOfClass:[NSData class]]) {
                
                
          
                
                
         //      NSString * responseString = [responseObject responseString ];
                
                
                
                NSString *result = [[NSString alloc] initWithData:responseObject  encoding:NSUTF8StringEncoding];

      


                    NSError *error = nil;
                
                
                NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
                
                
                
                if (resultDic != nil && error == nil){
                    
                   
                    
                }else{
                    
                    // 解析错误
                    
                }
                
                
                  _complete(1,operation,resultDic);
                
                
                
                
            }
            

          
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        
        
        if (_complete) {
            _complete(-1,operation,nil);
            
//            [SVProgressHUD showErrorWithStatus:@"网络连接失败"];
            
            [SVProgressHUD showImage:nil status:@"网络连接失败"];
            
        }
    }];
}
- (void) getWebAPIWithPath:(NSString *)path andParams:(NSDictionary *)params andMethodNode:(NSString *)node  completed:(WebAPIBlockRequest)complete {
   
   
   
    _complete = complete;
     NSString *url = [NSString stringWithFormat:@"%@/%@",path,node];
     url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    
    requestManager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    
     dispatch_queue_t queue = dispatch_queue_create("异步刷新", nil);
     dispatch_async(queue, ^(void) {
    [requestManager GET:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (_complete) {
            
            NSDictionary *resultDic;
            if ([responseObject isKindOfClass:[NSDictionary class]]) {
                resultDic =  responseObject;
            }else if([responseObject isKindOfClass:[NSData class]]){
                
                resultDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
            }
            
            if (resultDic) {
                _complete(1,operation,resultDic);
            }
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        if (_complete) {
            _complete(-1,operation,nil);
            
            NSLog(@"error:%@",error);
            [SVProgressHUD showErrorWithStatus:@"网路连接失败"];
        }
    }];
     });
}

- (void) getWebAPIWithParams:(NSDictionary *)params andMethodNode:(NSString *)node completed:(WebAPIBlockRequest)complete {
    
    
    dispatch_queue_t queue = dispatch_queue_create("异步刷新", nil);
    dispatch_async(queue, ^(void) {
    
    _complete = complete;
    NSString *url = [NSString stringWithFormat:@"%@/%@",kUrl,node];
    url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    requestManager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    
    [requestManager GET:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
//          dispatch_sync(dispatch_get_main_queue(), ^{
        if (_complete) {
            
            NSDictionary *resultDic;
            if ([responseObject isKindOfClass:[NSDictionary class]]) {
                resultDic =  responseObject;
            }else if([responseObject isKindOfClass:[NSData class]]){
            
             resultDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
             }
            
            if (resultDic) {
                _complete(1,operation,resultDic);
            }

        }
//          });
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//         dispatch_sync(dispatch_get_main_queue(), ^{
        if (_complete) {
            _complete(-1,operation,nil);
            
            NSLog(@"error:%@",error);
            [SVProgressHUD showErrorWithStatus:@"网路连接失败"];
        }
//              });
    }];
    });
}

- (void) getWebAPIWithPath:(NSString *)path andParams:(NSDictionary *)params  completed:(WebAPIBlockRequest)complete {
    _complete = complete;

    requestManager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    
    [requestManager GET:path parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        
        
        if (_complete) {
            
            if ([responseObject isKindOfClass:[NSData class]]) {
                NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
                    _complete(1,operation,resultDic);
            }
 
            if ([responseObject isKindOfClass:[NSDictionary class]]) {
                
                 _complete(1,operation,responseObject);
            }
            
            
        
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        if (_complete) {
            _complete(-1,operation,nil);
        }
    }];

    
   
}






////上传图片
////上传图片
- (void)updateAimg:(UIImage *)image andView:(UIView *)view andisHeadPic:(BOOL)isHeadPic andParams:(NSDictionary *)params andUrlString:(NSString *)string andComplete:(UpdataImgAPIRequest)completeRequest {
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes=[NSSet setWithObject:@"text/html"];
    
    
    
    NSData *  data = UIImageJPEGRepresentation(image,1);
    
    
    
    
    NSLog(@"操作前数据大小:%lu",(unsigned long)data.length);
    
    //大小控制
    float m = 0.1;
    float n = 1.0;
    
    while ((unsigned long)data.length>1024*200) {
        n = n - m;
        //压缩前
        unsigned long datalenght = data.length;
        //压缩后
        data = UIImageJPEGRepresentation(image,n);
        if (datalenght==data.length) {
            break;
        }
        
        NSLog(@"数据大小：%lu",(unsigned long)data.length);
    }
    NSLog(@"数据最终大小：%lu",(unsigned long)data.length);
    
    
    
    
    [manager POST:string parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        
        
        
        //[formData appendPartWithFileURL:[NSURL URLWithString:str] name:fileName error:nil];
        
        // [formData appendPartWithFormData:data name:fileName];
        //  [formData appendPartWithFileData:data name:@"===" fileName:fileName mimeType:@"image/jpg/file"];
        
        [formData appendPartWithFileData:data name:@"avator" fileName:@"sjjb10000.jpg" mimeType:@"image/jpg/file"];
        
    } success:^(AFHTTPRequestOperation *operation, id  responseObject) {
        
        
        
        NSData *doubi = responseObject;
        NSDictionary * dataDic = [NSJSONSerialization JSONObjectWithData:doubi options:NSJSONReadingAllowFragments error:nil];
        NSInteger result=[dataDic[@"code"]integerValue];
        
        completeRequest(result,nil,dataDic);
        
        if (result==0)
        {
            
        }
        else if (result==1)
        {
            
        }
        else
        {
            
        }
        
        
        
        
        
        
        
        
        
        [ UIApplication sharedApplication ] .networkActivityIndicatorVisible = NO ;
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
        [ UIApplication sharedApplication ] .networkActivityIndicatorVisible = NO ;
    }];
    [ UIApplication sharedApplication ] .networkActivityIndicatorVisible = YES ;
}






//上传图片
//上传图片
//- (void)sendMultipleUIImage:(UIImage *)image andView:(UIView *)view andisHeadPic:(BOOL)isHeadPic andParams:(NSDictionary *)params andUrlString:(NSString *)string andDateKey:(NSString *)key andComplete:(UpdataImgAPIRequest)completeRequest {
//    
//    //  image = [UIImage scaleToSize:CGSizeMake(100, 100) for:image];
//    
//    
//  //  JGProgressHUD *jgProgressHUD = [Commtools showPie2HUD:view];
//    MKNetworkEngine *engine = [[MKNetworkEngine alloc] init];
//    NSString *filename = @"";
//    NSData *data;
//    NSString *type = @"jpg";
//    
//    
//    data = UIImageJPEGRepresentation(image,1);
//    
//    
//    
//    
//    if (UIImagePNGRepresentation(image) == nil) {
//        data = UIImageJPEGRepresentation(image, 0.1);
//        type = @"jpg";
//    } else {
//        type = @"png";
//        data = UIImagePNGRepresentation(image);
//    }
//    if (isHeadPic) {
//        filename = [NSString stringWithFormat:@"%@%@%@",[CurrentDate timgString ], @"_photo.", type];
//    } else {
//        filename = [NSString stringWithFormat:@"%@_%@.%@", @"uid", [Commtools getCurrentDataUpdateImg], type];
//    }
//    NSLog(@"————————文件名字：%@", filename);
//    
//    NSLog(@"操作前数据大小:%lu",(unsigned long)data.length);
//    
//    //大小控制
//    float m = 0.1;
//    float n = 1.0;
//    
//    while ((unsigned long)data.length>1024*200) {
//        n = n - m;
//        //压缩前
//        unsigned long datalenght = data.length;
//        //压缩后
//        data = UIImageJPEGRepresentation(image,n);
//        if (datalenght==data.length) {
//            break;
//        }
//        
//        NSLog(@"数据大小：%lu",(unsigned long)data.length);
//    }
//    NSLog(@"数据最终大小：%lu",(unsigned long)data.length);
//    
//    
//    
//    
//    
//    
//    MKNetworkOperation *op = [engine operationWithURLString:string params:params httpMethod:@"POST"];
//    
//    
//    [op addData:data forKey:key mimeType:type fileName:filename];
//    
//    
//    
//    
//    
//    [op addCompletionHandler:^(MKNetworkOperation *completedOperation) {
//        
//        
//        NSLog(@"%@", completedOperation.responseString);
//        [self imgStrToDict:completedOperation.responseString andFilename:filename code:1 complete:completeRequest];
//        
//        
//        
//    }           errorHandler:^(MKNetworkOperation *completedOperation, NSError *error) {
//        
//        
//        NSLog(@"mknetwork error : %@", error.debugDescription);
//    }];
//    
//    
//    [op onUploadProgressChanged:^(double progress) {
//        
//        //        NSLog(@"%.2f", progress * 100.0);
//    //   [Commtools incrementHUD:jgProgressHUD progress:(int) (progress * 100.0)];
//        
//      //  [SVProgressHUD showImage:nil status:@"正在上传图片"];
//        
//        
//    }];
//    
//    
//    
//    [engine enqueueOperation:op];
//}




//
//- (void)sendQMultipleUIImage:(NSArray *)images andView:(UIView *)view andisHeadPic:(BOOL)isHeadPic andParams:(NSDictionary *)params andUrlString:(NSString *)string andDateKey:(NSString *)key andComplete:(UpdataImgAPIRequest)completeRequest {
//    
//    //  image = [UIImage scaleToSize:CGSizeMake(100, 100) for:image];
//    
//    
//   // JGProgressHUD *jgProgressHUD = [Commtools showPie2HUD:view];
//    MKNetworkEngine *engine = [[MKNetworkEngine alloc] init];
//    NSString *filename = @"";
//    NSData *data;
//    NSString *type = @"jpg";
//    
//    
//    
//    for (UIImage *image in images) {
//        
//        data = UIImageJPEGRepresentation(image,1);
//        
//        
//        
//        
//        if (UIImagePNGRepresentation(image) == nil) {
//            data = UIImageJPEGRepresentation(image, 0.1);
//            type = @"jpg";
//        } else {
//            type = @"png";
//            data = UIImagePNGRepresentation(image);
//        }
//        
//    }
//    
//
//
//    
//    
//    
//    
//    
//    
//    MKNetworkOperation *op = [engine operationWithURLString:string params:params httpMethod:@"POST"];
//    
//    
//    [op addData:data forKey:key mimeType:type fileName:filename];
//    
//    
//    
//    
//    
//    [op addCompletionHandler:^(MKNetworkOperation *completedOperation) {
//        
//        
//        NSLog(@"%@", completedOperation.responseString);
//        [self imgStrToDict:completedOperation.responseString andFilename:filename code:1 complete:completeRequest];
//        
//        
//        
//    }           errorHandler:^(MKNetworkOperation *completedOperation, NSError *error) {
//        
//        
//        NSLog(@"mknetwork error : %@", error.debugDescription);
//    }];
//    
//    
//    [op onUploadProgressChanged:^(double progress) {
//        
//        //        NSLog(@"%.2f", progress * 100.0);
//       // [Commtools incrementHUD:jgProgressHUD progress:(int) (progress * 100.0)];
//        
//        //  [SVProgressHUD showImage:nil status:@"正在上传图片"];
//        
//        
//    }];
//    
//    
//    
//    [engine enqueueOperation:op];
//}





- (void)imgStrToDict:(NSString *)json andFilename:(NSString *)filename code:(int)state complete:(UpdataImgAPIRequest)completeRequest {
    
    
    NSData *jsonData = [json dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableLeaves error:&err];
    if (err) {
        NSLog(@"json解析失败：%@", err);
        completeRequest(0, nil, filename);
    } else {
        
        
        
        NSLog(@"state:%d,responseObject:%@", state, [self logDic:resultDic]);
        completeRequest(state, resultDic, filename);
    }
}
- (NSString *)logDic:(NSDictionary *)dic {
    NSString *tempStr1 = [[dic description] stringByReplacingOccurrencesOfString:@"\\u" withString:@"\\U"];
    NSString *tempStr2 = [tempStr1 stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
    NSString *tempStr3 = [[@"\"" stringByAppendingString:tempStr2] stringByAppendingString:@"\""];
    NSData *tempData = [tempStr3 dataUsingEncoding:NSUTF8StringEncoding];
    NSString *str = [NSPropertyListSerialization propertyListWithData:tempData options:NSPropertyListImmutable format:NULL error:NULL];
    //    NSString *str = [NSPropertyListSerialization propertyListFromData:tempData mutabilityOption:NSPropertyListImmutable format:NULL errorDescription:NULL];
    //    NSLog(@"%@", str);
    if (str == nil) str = [dic description];
    return str;
}


#pragma mark---同步判断医院还是个人

//-(void)loginInWithMob:(NSString *)mob
//{
//    int time=[[NSDate date] timeIntervalSince1970];
//
//    
//    NSString *signString;
//    
//    
//    signString=[NSString stringWithFormat:@"%@=%d&key=syinchung@20150330",@"time",time];
//    
//    
//    signString=[EncoderMd5 getMd5_32Bit_String:signString];
//    
//    
//    
//    NSMutableDictionary *parms=[@{
//                                  
//                                  @"mobile":mob
//                                  
//                                  } mutableCopy];
// 
//    
//    [parms setObject:signString forKey:@"sign"];
//    [parms setObject:[NSString stringWithFormat:@"%d",time] forKey:@"time"];
//    
//    NSString *parmString=[self parseParams:parms];
//
//    
//    NSData * body = [parmString dataUsingEncoding:NSUTF8StringEncoding];
//    
//    
//    NSString *url = [kBaseURL stringByAppendingFormat:@"%@",@"api/user/getUserType"];
//
//    
//   
//    //第二步，通过URL创建可变的request请求（只有创建可变的request才能设置POST请求）
//    NSMutableURLRequest * request1 = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:5];
//    //timeoutInterval:post超时最大时间是240秒,在方法中设置多少秒也没用。
//    
//    //第三步，设置POST请求方式
//    [request1 setHTTPMethod:@"POST"];
//
//
//    [request1 setHTTPBody:body];
//    //第五步，连接服务器
//    NSData * data = [NSURLConnection sendSynchronousRequest:request1 returningResponse:nil error:nil];
//    
//    
//    
//    if (data&&data.length>2) {
//        
//        NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
//        
//        
//        if ([resultDic[@"code"] isEqualToString:@"1"]) {
//            
//            if ([resultDic[@"type"] isEqualToString:@"1"]) {
//                
//                ApplicationDelegate.useType=@"hospital";
//            }
//            
//            if ([resultDic[@"type"] isEqualToString:@"0"]) {
//                
//                ApplicationDelegate.useType=@"person";
//            }
//            
//            
//            
//        }
//    }
//    
//    
//
//
//
//    
//    
//    
//
//
// 
//
//}



//把NSDictionary解析成post格式的NSString字符串
-(NSString *)parseParams:(NSDictionary *)params{
    NSString *keyValueFormat;
    NSMutableString *result = [NSMutableString new];
    //实例化一个key枚举器用来存放dictionary的key
    NSEnumerator *keyEnum = [params keyEnumerator];
    id key;
    while (key = [keyEnum nextObject]) {
        keyValueFormat = [NSString stringWithFormat:@"%@=%@&",key,[params valueForKey:key]];
        [result appendString:keyValueFormat];
        NSLog(@"post()方法参数解析结果：%@",result);
    }
    return result;
}



@end
